# -*- coding: utf-8 -*-

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from timelineapp.models import Timeline 
from eventapp.forms import EventForm
from eventapp.models import Asset, AssetType, Event
from eventapp.forms import AssetForm
from datetime import datetime

def search_events(request, timeline_id):
    form = request.GET
    tid = timeline_id
        
    if ("date" in form):
        event_form = EventForm()
        search_date = datetime.strptime(form["date"], '%d/%m/%Y')
        date = form["date"]
        events = Timeline.objects.get(pk=timeline_id).events.filter(date__exact=search_date)
        
        if "action" in form:
            action = form["action"]
            events_count = len(events)
        
            if (action == "Search"):
                # Displays events found if any. If there are no events, the form to add a new one. 
                if events:
                    action = "List"
                    return render_to_response('events.html', locals())
                
                else:
                    action = "Add"
                    return HttpResponseRedirect('/timelines/%s/events/new?date=%s&events_count=0' % (timeline_id, date))
            elif (action == "Add"):
                return HttpResponseRedirect('/timelines/%s/events/new?date=%s&events_count=%s' % (timeline_id, date, events_count)) 
            
            elif (action == "Edit"):
                if ("event_id" in form):
                    event_id = form["event_id"]
                return HttpResponseRedirect('/timelines/%s/events/%s/edit' % (timeline_id, event_id))
            
    local_vars = {"action": "Search", "events_count": 0, "timeline_id": timeline_id}
    return render_to_response('search_form.html', local_vars)
    
def add_event(request, timeline_id):
    user_id = request.user.id
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/user/login?previous=%s' % request.path)
    
    date = ""
    action = "Add"
    events_count = 0
    if request.method == 'POST':
        event_form = EventForm(request.POST)        
        
        if event_form.is_valid():
            # creates event
            event = event_form.save(user_id)
            
            # adds event to the timeline
            timeline = Timeline.objects.get(id = timeline_id)
            timeline.events.add(event)
            
            # displays timeline
            return HttpResponseRedirect('/timelines/%s/events/%s/assets' % (timeline_id, event.id))
    
    elif request.method == 'GET':
        if ("date" in request.GET):
            date = request.GET["date"]
        if ("events_count" in request.GET):
            events_count = int(request.GET["events_count"])
    
    event_form = EventForm()
    return render_to_response("events_form.html", locals()) 
    
def add_event_to_timeline(request, timeline_id):
    user_id = request.user.id
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/user/login?previous=%s' % request.path)
    
    if request.method == 'POST':
        event_form = EventForm(request.POST)
        
        if event_form.is_valid():
            print event_form.cleaned_data
            
            # creates event
            event = event_form.save(user_id)
            
            # adds event to the timeline
            timeline = Timeline.objects.get(id = timeline_id)
            timeline.events.add(event)
            
            # displays timeline
            return HttpResponseRedirect('/timelines/%s/events/%s/assets' % (timeline_id, event.id))
        
        else:
            # Some problem in the data sent.
            event_form = EventForm(request.POST)
            local_vars = {"action": "Add", 
                          "events_count": 0, 
                          "timeline_id": timeline_id, 
                          "event_form": event_form,
                          "date": request.POST["date"]}
            
    elif request.method == 'GET':
        form = request.GET
        
        # Default action: Search. First action when adding a new event. 
        if ("action" not in form):
            local_vars = {"action": "Search", "events_count": 0, "timeline_id": timeline_id}
            
        else:
            action = form["action"]
            event_form = EventForm()
            
            if (action == "Search"):
                
                # Get date to search for events.
                if ("search_date" in form):
                    search_date = datetime.strptime(form["search_date"], '%d/%m/%Y')
                    date = form["search_date"]
                    
                    events = Timeline.objects.get(pk=timeline_id).events.filter(date__exact=search_date)
            
                    # Displays events found if any. If there are no events, the form to add a new one. 
                    if events:
                        action = "List"
                        events_count = len(events)
                    
                    else:
                        action = "Add"
                        events_count = 0
                    
                    local_vars = {"action": action, 
                                  "events_count": events_count, 
                                  "date": date, 
                                  "events": events, 
                                  "event_form": event_form,
                                  "timeline_id": timeline_id,}                    
            else:
                event_form = EventForm()
                date = ""
                if ("date" in form):
                    date = form["date"]
                                
                events_count = 0
                if ("events_count" in form):
                    events_count = form["events_count"]
                                        
                local_vars = {"action": action, 
                              "events_count": events_count, 
                              "date": date, 
                              "event_form": event_form,
                              "timeline_id": timeline_id}

    return render_to_response('events_form.html', local_vars)

def add_assets_to_event(request, timeline_id, event_id):
    message = ""
    user_id = request.user.id # change for logged user
    event_assets = []
    
    if request.method == "POST":
        asset_form = AssetForm(request.POST)

        if asset_form.is_valid():
            # creates asset
            asset = asset_form.save(user_id)
            
            # adds asset to event
            event = Event.objects.get(pk = event_id)
            event.assets.add(asset)
            
            message = str(asset.asset_type) + " incluído com sucesso."
            
            event_assets = Asset.objects.filter(event = event.id)
            
            
    asset_types = AssetType.objects.all().order_by('name')
    asset_form = AssetForm()
    event = Event.objects.get(pk=int(event_id))

    return render_to_response('assets_form.html', {"asset_types": asset_types,
                                                   "asset_form": asset_form,
                                                   "event": event,
                                                   "timeline_id": timeline_id,
                                                   "event_id": event_id,
                                                   "message": message,
                                                   "event_assets" : event_assets })
def edit_event(request, timeline_id, event_id):
    action = "Edit"
    event_form = EventForm()
    
    if (request.method == 'POST'):
        event_form = EventForm(request.POST)
        
        if event_form.is_valid():
            cd = event_form.cleaned_data
            print cd
            
            event = Event.objects.get(pk=event_id)
            event.title = cd["title"]
            event.description = cd["description"]
            event.date = cd["date"] 
            event.save()
            
            # adds event to the timeline
            timeline = Timeline.objects.get(pk=timeline_id)
            timeline.events.add(event)
            
            # displays form to add assets
            return HttpResponseRedirect('/timelines/%s/events/%s/assets' % (timeline_id, event.id))
        
    event = Event.objects.get(pk=event_id)
    date = event.date.strftime("%d/%m/%Y")
        
    return render_to_response('events_form.html', locals())